package com.wxq.schoolmap;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import com.wxq.draw.DrawDBTool;
import com.wxq.utility.QUtility;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MoreInfoActivity extends Activity {

	Button modifyBtn;
	Button cancelBtn;
	ListView moreInfoLV;
	
	String spotId;
	String unitTypeId;
	String xmlContent;
	List<Map<String, String>> fieldInfoList;
	DrawDBTool dbTool;
	SimpleAdapter simpleAdapter;
	int index;
	ListView multiChoiceLV;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.moreinfo_acitivity);	
		
		modifyBtn = (Button) findViewById(R.id.commitBtn);
		cancelBtn = (Button) findViewById(R.id.cancelBtn);
		moreInfoLV = (ListView) findViewById(R.id.moreInfoLV);
		
		Intent intent = getIntent();
		spotId = intent.getStringExtra("spotId");
		unitTypeId = intent.getStringExtra("unitTypeId");	
		xmlContent = intent.getStringExtra("xmlContent");
		
		//获取fieldInfoList
		dbTool = new DrawDBTool(this);
		fieldInfoList = dbTool.getPOITypeFields(unitTypeId);
		//fieldInfoList添加现有信息
		addContent2FieldList();
		//为列表装填数据
		addAllInfoItems();
		
		moreInfoLV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					final int position, long id) {
				// 弹出界面修改内容，完毕之后刷新List
				Map<String, String> map = fieldInfoList.get(position);
				String comboModeStr = map.get("ComboMode");
				if (comboModeStr == null || "".equals(comboModeStr)) {
					comboModeStr = "0";
				}
				int comboMode = Integer.parseInt(comboModeStr);
				LayoutInflater inflater=(LayoutInflater)MoreInfoActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				if (comboMode == 0) {
					//文字
					final View v = inflater.inflate(R.layout.moreinfo_text_diag, null);
					new AlertDialog.Builder(MoreInfoActivity.this)
					.setTitle("请输入内容")
					.setView(v)
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 确定动作
							EditText contentET = (EditText) v.findViewById(R.id.content);
							String content = contentET.getText().toString();
							fieldInfoList.get(position).put("content", content);
							simpleAdapter.notifyDataSetChanged();
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 取消	
						}
					}).show();
				}
				else if (comboMode == 1) {
					//单选
					index = -1;
					String ListSource = map.get("ListSource");
					String [] tempArray = TextUtils.split(ListSource.trim(), "\\|");
					List<String> tempList = new ArrayList<String>();
					for (int i = 0; i < tempArray.length; i++) {
						if(! TextUtils.isEmpty(tempArray[i]) )
						{
							tempList.add(tempArray[i]);
						}
					}
					final String [] array = new String [tempList.size()];
					for (int i = 0; i < tempList.size(); i++) {
						array[i] = tempList.get(i);
					}

					new AlertDialog.Builder(MoreInfoActivity.this)
					.setTitle("请选择")
					.setSingleChoiceItems(array, -1, new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 获得选择
							index = which;
						}
					})
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 确定动作
							String content = "";
							if (index>=0 && index <array.length) {
								content = array[index];
							}
							fieldInfoList.get(position).put("content", content);
							simpleAdapter.notifyDataSetChanged();
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 取消	
						}
					}).show();
				}
				else if (comboMode == 2) {
					//多选
					String ListSource = map.get("ListSource");
					String [] tempArray = TextUtils.split(ListSource.trim(), "\\|");
					List<String> tempList = new ArrayList<String>();
					for (int i = 0; i < tempArray.length; i++) {
						if(! TextUtils.isEmpty(tempArray[i]) )
						{
							tempList.add(tempArray[i]);
						}
					}
					final String [] array = new String [tempList.size()];
					for (int i = 0; i < tempList.size(); i++) {
						array[i] = tempList.get(i);
					}
					
					boolean [] boolArray = new boolean[array.length];
					for (int i = 0; i < boolArray.length; i++) {
						boolArray[i] = false;
					}
					
					AlertDialog ad = new AlertDialog.Builder(MoreInfoActivity.this)
					.setTitle("请选择")
					.setMultiChoiceItems(array, boolArray, new DialogInterface.OnMultiChoiceClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which, boolean isChecked) {
							// 
							
						}
					})
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 确定动作
							String content = "";
							
							for (int i = 0;i < array.length ;i++) {
								if (multiChoiceLV.getCheckedItemPositions().get(i)) {
									content += multiChoiceLV.getAdapter().getItem(i)+"; ";
								}
							}
							
							fieldInfoList.get(position).put("content", content);
							simpleAdapter.notifyDataSetChanged();
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 取消	
						}
					}).create();
					multiChoiceLV = ad.getListView();
					ad.show();
				}
			}
		});
		
		cancelBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		modifyBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//提交
				StringWriter stringWriter = new StringWriter();
				try {    
		            // 获取XmlSerializer对象     
		            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();    
		            XmlSerializer xmlSerializer = factory.newSerializer();    
		            // 设置输出流对象    
		            xmlSerializer.setOutput(stringWriter); 
		            //xmlSerializer.startDocument("utf-8", true);
		            
		            xmlSerializer.startTag(null, "Unit");
		            for (int i = 0; i < fieldInfoList.size(); i++) {
						Map<String, String> map = fieldInfoList.get(i);
						String content = map.get("content");
						if (! TextUtils.isEmpty(content) &&  ! "false".equals(content.toLowerCase())) {
							String key = map.get("Field");
							xmlSerializer.startTag(null, key);
							xmlSerializer.text(content);
							xmlSerializer.endTag(null, key);
						}
					}
		            xmlSerializer.endTag(null, "Unit");
		            xmlSerializer.endDocument(); 
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				String xmlContent = stringWriter.toString();
				int rows = dbTool.updateMoreInfo(spotId, xmlContent);
				if (rows>0) {
					Toast.makeText(MoreInfoActivity.this, "更新更多信息成功！", Toast.LENGTH_LONG).show();
				}
				else {
					Toast.makeText(MoreInfoActivity.this, "未更新更多信息！", Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	
	public void addAllInfoItems() {
		if (fieldInfoList == null) {
			return;
		}
		simpleAdapter = new
				 SimpleAdapter(this, 
						 fieldInfoList, 
						 R.layout.moreinfo_modify_item, 
						 new String[]{"Name","content"}, 
						 new int []{R.id.name,R.id.content});
		moreInfoLV.setAdapter(simpleAdapter);
	}
	
	public void addContent2FieldList() {
		//取得现有信息的map
		Map<String, String> moreInfoMap = QUtility.getMoreInfoMap(xmlContent);
		//对fieldInfoList进行添加现有信息
		for (int i = 0; i < fieldInfoList.size(); i++) {
			String field = fieldInfoList.get(i).get("Field");
			if (moreInfoMap.containsKey(field)) {
				fieldInfoList.get(i).put("content", moreInfoMap.get(field));
			}
			else {
				fieldInfoList.get(i).put("content", "");
			}
		}
	}

	@Override
	protected void onDestroy() {
		dbTool.close();
		super.onDestroy();
	}
}
